﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using Aspose.Words;

namespace MyHelper
{
    public class WordHelper
    {
        /// <summary>
        /// 根据模板新建一个有数据的word文档
        /// </summary>
        /// <param name="dic">键是模板里面的基本字段，值是你要替换的值</param>
        /// <param name="modelPath">模板在的路径(加文件名)</param>
        /// <param name="newPath">要导出的新的word的路径(加文件名)</param>
        /// <returns></returns>
        public static string ExportWordByMould(Dictionary<string,string> dic,string modelPath,string newPath)
        {

            try
            {
                Document doc = new Document();
                //使用特殊字符串替换
                doc = new Document(modelPath);
                foreach (var key in dic.Keys)
                {
                    if (key != "头像")
                    {
                        var repStr = string.Format("&{0}&", key);
                        doc.Range.Replace(repStr, dic[key], false, false);
                    }
                    else
                    {
                        Regex reg = new Regex("&头像&");
                        doc.Range.Replace(reg, new ReplaceAndInsertImage(dic[key]), false);
                    }
                }
                doc.Save(newPath);//也可以保存为1.doc 兼容03-07 
                return "操作成功";
            }
            catch (Exception ex)
            {
                return "操作失败:"+ex.Message;
            }

        }
    }
    public class ReplaceAndInsertImage : IReplacingCallback
    {
        /// <summary>
        /// 需要插入的图片路径
        /// </summary>
        public string url { get; set; }
        public ReplaceAndInsertImage(string url)
        {
            this.url = url;
        }
        public ReplaceAction Replacing(ReplacingArgs e)
        {
            //获取当前节点
            var node = e.MatchNode;
            //获取当前文档
            Document doc = node.Document as Document;
            DocumentBuilder builder = new DocumentBuilder(doc);
            //将光标移动到指定节点
            builder.MoveTo(node);
            //插入图片
            builder.InsertImage(url);
            return ReplaceAction.Replace;
        }
    }

     //使用书签操作
            //Document doc = new Document("c:/1.docx");
            //DocumentBuilder builder = new DocumentBuilder(doc);
            //foreach (var key in dic.Keys)
            //{
            //    builder.MoveToBookmark(key);
            //    if (key != "头像")
            //    {
            //        builder.Write(dic[key]);
            //    }
            //    else
            //    {
            //        builder.InsertImage(dic[key]);
            //    }
            //}
            //doc.Save("C:/书签操作.docx");//也可以保存为1.doc 兼容03-07
            //Console.WriteLine("已经完成书签操作");
}
